﻿dmgis.olmap = dmgis.olmap ? dmgis.olmap : {};
dmgis.olmap = (function () {
})

//GaodeLayer
dmgis.olmap.GaodeLayer = dmgis.olmap.GaodeLayer ? dmgis.olmap.GaodeLayer : {};
dmgis.olmap.GaodeLayer = (function (layerName, options) {
    var options = options ? options : {};
    var attributions;
    if (options.attributions !== undefined) {
        attributions = option.attributions;
    } else {
        attributions = ['&copy; <a class="ol-attribution-amap" ' + 'href="http://ditu.amap.com/">' + "高德地图</a>"];
    }

    var url;
    if (options.mapType == dmgis.enum.GaodeType.VEC) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7";
    } else if (options.mapType == dmgis.enum.GaodeType.VEC0) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7";
    } else if (options.mapType == dmgis.enum.GaodeType.IMG) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6";
    } else if (options.mapType == dmgis.enum.GaodeType.IMG0) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=6";
    } else if (options.mapType == dmgis.enum.GaodeType.RIMG) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8";
    } else if (options.mapType == dmgis.enum.GaodeType.RIMG0) {
        url = "http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=8";
    }
    var source = new ol.source.XYZ({
        attributions: attributions,
        crossOrigin: "anonymous", //跨域
        cacheSize: options.cacheSize,
        projection: ol.proj.get("EPSG:3857"),
        url: url,
        wrapX: options.wrapX !== undefined ? options.wrapX : true
    });
    var options = {
        title: layerName,
        source: source
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.GaodeLayer, ol.layer.Tile);

//BaiduLayer
dmgis.olmap.BaiduLayer = dmgis.olmap.BaiduLayer ? dmgis.olmap.BaiduLayer : {};
dmgis.olmap.BaiduLayer = (function (layerName, options) {
    var options = options ? options : {};
    var attributions;
    if (options.attributions !== undefined) {
        attributions = option.attributions;
    } else {
        attributions = ['&copy; <a class="ol-attribution-baidumap" ' + 'href="http://map.baidu.com/">' + "百度地图</a>"];
    }

    var extent = [72.004, 0.8293, 137.8347, 55.8271];

    var baiduMercator = new ol.proj.Projection({
        code: "baidu",
        extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
        units: "m"
    });

    ol.proj.addProjection(baiduMercator);
    ol.proj.addCoordinateTransforms("EPSG:4326", baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll);
    ol.proj.addCoordinateTransforms("EPSG:3857", baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc);
    var resolutions = [];
    //重新定义分辨率
    for (var i = 0; i < 19; i++) {
        resolutions[i] = Math.pow(2, 18 - i);
    }
    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions,
        extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
        tileSize: [256, 256]
    });
    var satUrls = [0, 1, 2, 3, 4].map(function (sub) {
        return "http://shangetu" + sub + ".map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&fm=46&udt=20150601";
    });
    var urls = [0, 1, 2, 3, 4].map(function (sub) {
        return "http://online" + sub + ".map.bdimg.com/onlinelabel/qt=tile&x={x}&y={y}&z={z}&v=009&styles=pl&udt=20170301&scaler=1&p=1";
    });
    var source = new ol.source.TileImage({
        attributions: attributions,
        crossOrigin: "anonymous", //跨域
        cacheSize: options.cacheSize,
        // projection: ol.proj.get('EPSG:3857'),
        projection: "baidu",
        tileGrid: tilegrid,
        tileUrlFunction: function (tileCoord, pixelRatio, proj) {
            //重写索引检索方法
            if (!tileCoord) return "";

            var z = tileCoord[0];
            var x = tileCoord[1];
            var y = tileCoord[2];
            var hash = (x << z) + y;
            var index = hash % urls.length;
            index = index < 0 ? index + urls.length : index;
            if (options.mapType == dmgis.enum.BaiduType.IMG) {
                return satUrls[index].replace("{x}", x).replace("{y}", y).replace("{z}", z);
            }
            return urls[index].replace("{x}", x).replace("{y}", y).replace("{z}", z);

        },
        wrapX: options.wrapX !== undefined ? options.wrapX : true
    });

    var options = {
        title: layerName,
        source: source
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.BaiduLayer, ol.layer.Tile);

//TiandituLayer
dmgis.olmap.TiandituLayer = dmgis.olmap.TiandituLayer ? dmgis.olmap.TiandituLayer : {};
dmgis.olmap.TiandituLayer = (function (layerName, options) {
    var options = options ? options : {};
    var attributions;
    if (options.attributions !== undefined) {
        attributions = option.attributions;
    } else {
        attributions = ['&copy; <a class="ol-attribution-tianmap" ' + 'href="http://www.tianditu.cn/">' + "天地图</a>"];
    }

    var url;
    if (options.mapType == dmgis.enum.TiandituType.IMG) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //基础影像
        //title = "基础影像";
    } else if (options.mapType == dmgis.enum.TiandituType.CIA) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //带标签影像
        //title = "基础影像标签";
    } else if (options.mapType == dmgis.enum.TiandituType.VEC) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //基础地图
        //title = "基础地图";
    } else if (options.mapType == dmgis.enum.TiandituType.CVA) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //基础地图
        //title = "基础地图标签";
    } else if (options.mapType == dmgis.enum.TiandituType.TER) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //地形图
        //title = "地形图";
    } else if (options.mapType == dmgis.enum.TiandituType.CTA) {
        url = "http://t{0-4}.tianditu.com/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=3b41248c204d6f92ca4fbd7da0386da6"; //地形图
        //title = "地形图标注";
    }

    var source = new ol.source.XYZ({
        attributions: attributions,
        projection: ol.proj.get("EPSG:3857"),
        cacheSize: options.cacheSize,
        // crossOrigin: "anonymous",
        opaque: options.opaque !== undefined ? options.opaque : true,
        maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold, //异常处理
        url: url,
        wrapX: options.wrapX
    });
    var options = {
        title: layerName,
        source: source
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.TiandituLayer, ol.layer.Tile);

//OSMLayer
dmgis.olmap.OSMLayer = dmgis.olmap.OSMLayer ? dmgis.olmap.OSMLayer : {};
dmgis.olmap.OSMLayer = (function (layerName, options) {
    var source = new ol.source.OSM();
    var options = {
        title: layerName,
        source: source
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.OSMLayer, ol.layer.Tile);

//ArcgisLayer
dmgis.olmap.ArcgisLayer = dmgis.olmap.ArcgisLayer ? dmgis.olmap.ArcgisLayer : {};
dmgis.olmap.ArcgisLayer = (function (layerName, tileUrl, options) {
    var options = options ? options : {};
    var projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    // 坐标原点
    var origin = options.origin;
    // 分辨率
    var resolutions = options.resolutions;
    //地图范围
    var fullExtent = options.extent;
    //瓦片大小
    var tileSize = options.tileSize ? options.tileSize : 256;
    var maxZoom = options.maxZoom ? options.maxZoom : 18;
    var minZoom = options.minZoom ? options.minZoom : 0;
    var tileGrid = new ol.tilegrid.TileGrid({
        tileSize: tileSize,
        origin: origin,
        extent: fullExtent,
        resolutions: resolutions
    });
    // 瓦片数据源
    var source = new ol.source.XYZ({
        tileGrid: tileGrid,
        projection: projection,
        url: tileUrl,
        minZoom: minZoom,
        maxZoom: maxZoom
    });

    var options = {
        title: layerName,
        source: source
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.ArcgisLayer, ol.layer.Tile);


//----------------DM瓦片----------------//
dmgis.olmap.TileLayer = dmgis.olmap.TileLayer ? dmgis.olmap.TileLayer : {};
dmgis.olmap.TileLayer = (function (layerName, mapService, tileType, options) {
    var layerName = layerName;
    var mapService = mapService;
    var tileType = tileType;
    var options = options ? options : {};
    var resolutions = [];
    var minx = options.extent[0];
    var miny = options.extent[1];
    var maxx = options.extent[2];
    var maxy = options.extent[3];
    var projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    var tileSize = options.tileSize ? options.tileSize : 256;
    var maxZoom = options.maxZoom ? options.maxZoom : 18;
    var minZoom = options.minZoom ? options.minZoom : 1;
    // 计算百度使用的分辨率
    for (var i = 0; i <= maxZoom; i++) {
        resolutions[i] = (maxx - minx) / Math.pow(2, i) / tileSize;
    }

    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [minx, maxy], // 设置原点坐标
        resolutions: resolutions, // 设置分辨率
        tileSize: tileSize,
        minZoom: minZoom,
        maxZoom: maxZoom,
        extent: options.extent
    });
    var source = new ol.source.XYZ({
        extent: options.extent,
        tileGrid: tilegrid,
        maxZoom: maxZoom,
        minZoom: minZoom,
        projection: projection,
        tileUrlFunction: function (tileCoord) {
            ;
            var z = tileCoord[0];
            var y = Math.pow(2, z) - 1 - (Math.abs(tileCoord[2]) - 1);
            var x = tileCoord[1];
            if (tileType == dmgis.enum.DMGISTileType.Service) {
                var imgUrl = mapService + "/dts/GetDmgisTileImage/" + layerName + "/{x}/{y}/{z}";
                return imgUrl.replace("{z}", z).replace("{x}", x).replace("{y}", y);
            } else {
                var imgUrl = mapService + "/" + layerName + "/{z}/{y}/{x}.jpg";
                return imgUrl.replace("{z}", z).replace("{x}", x).replace("{y}", y);
            }
        }
    });
    var options = {
        title: layerName,
        source: source,
        wrapX: true
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.TileLayer, ol.layer.Tile);


//----------------DM服务ServiceLayer----------------//
dmgis.olmap.ServiceLayer = dmgis.olmap.ServiceLayer ? dmgis.olmap.ServiceLayer : {};
dmgis.olmap.ServiceLayer = (function (layerName, mapService, options) {
    var options = options ? options : {};
    this.imgsvrParam = null;
    this.service = null;
    this.mapService = mapService;
    this.serverName = layerName;
    this.maxZoom = options.maxZoom ? options.maxZoom : 18;
    this.minZoom = options.minZoom ? options.minZoom : 0;
    this.opacity = options.opacity ? options.opacity : 1;
    this.projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    this.ImgMapService = new dmgis.object.ImgServiceParam();
    ol.layer.Image.call(this, options);
})
ol.inherits(dmgis.olmap.ServiceLayer, ol.layer.Image);
dmgis.olmap.ServiceLayer.prototype.InitService = function () {
    ;
    var url = this.mapService + "/dms/GetService/" + this.serverName;
    var obj = this;
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }

            var svr = new dmgis.service.GetProjServers(data);
            obj.service = svr;
            obj.ImgMapService.ResetService(svr);
            obj.ImgMapService.serverName = obj.serverName;

        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });
}
dmgis.olmap.ServiceLayer.prototype.RefreshMap = function (ImgServiceParam, zoom) {
    var iLevel = zoom;
    if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
        this.ImgMapService = ImgServiceParam;
        if (this.ImgMapService.layers != null) {
            var extent = this.ImgMapService.DispRect;
            var mapextent = map.getView().calculateExtent(map.getSize());
            var url = this.mapService + "/dms/GetImage/" + this.serverName + "?param=" + encodeURIComponent(this.ImgMapService.GetXmlString());
            var imagesource = new ol.source.ImageStatic({
                url: url,
                projection: this.projection,
                crossOrigin: "Anonymous",
                // imageExtent: mapextent
                imageExtent: [extent.minx, extent.miny, extent.maxx, extent.maxy]
            });
            this.setSource(imagesource);
        }
    }
}
dmgis.olmap.ServiceLayer.prototype.GetImgSvrParam = function () {
    return this.ImgMapService;
}
dmgis.olmap.ServiceLayer.prototype.getLayers = function () {
    return this.service.layers
}
//属性服务
dmgis.olmap.ServiceLayer.prototype.GetFeatureMapService = function (ActiveLayerName) {
    var dmFeatureMapService = new dmgis.object.FeatureServiceParam();
    dmFeatureMapService.serverName = this.ImgMapService.serverName; //服务名称
    dmFeatureMapService.strlayername = ActiveLayerName;
    
    return dmFeatureMapService;
}
dmgis.olmap.ServiceLayer.prototype.SendFeatureMapService = function (svr) {
    var self = this
    this.serviceurl = this.mapService
    var url = this.serviceurl + "/dms/GetFeature/" + svr.serverName + "?param=" + encodeURIComponent(svr.GetXmlString());

    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }
            // ;
            var dmGetFeature = new dmgis.service.GetFeatureInfo(data);
            ;
            self.HandleFeatureInfo(dmGetFeature);
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}
//缓冲区
dmgis.olmap.ServiceLayer.prototype.GetBufferMapService = function (ActiveLayerName) {
    var dmBufferMapService = new dmgis.object.BufferServiceParam();
    dmBufferMapService.serverName = this.ImgMapService.serverName; //服务名称
    dmBufferMapService.strlayername = ActiveLayerName; //查询的图层
    dmBufferMapService.type = 0; //0为索引   1为实体号
    dmBufferMapService.no = 3;
    
    return dmBufferMapService;
}
dmgis.olmap.ServiceLayer.prototype.SendBufferMapService = function (svr) {
    var self = this
    this.serviceurl = this.mapService
    var url = this.serviceurl + "/dms/GetSpatialAnalyse/" + svr.serverName + "?param=" + encodeURIComponent(svr.GetXmlString());
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }

            var dmGetBuffer = new dmgis.service.GetBufferInfo(data);
         
            self.HandleBufferInfo(dmGetBuffer);

        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}
//路径分析
dmgis.olmap.ServiceLayer.prototype.GetPathMapService = function (ActiveLayerName) {
    var dmPathMapService = new dmgis.object.PathServiceParam();
    dmPathMapService.serverName = this.ImgMapService.serverName; //服务名称
    dmPathMapService.strlayername = ActiveLayerName; //查询的图层
    return dmPathMapService;
}
dmgis.olmap.ServiceLayer.prototype.SendPathMapService = function (svr) {
    var self = this
    this.serviceurl = this.mapService
    var url = this.serviceurl + "/dms/GetPathAnalyse/" + svr.serverName + "?param=" + encodeURIComponent(svr.GetXmlString());
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }

            var dmGetPath = new dmgis.service.GetPathInfo(data);
            self.HandlePathInfo(dmGetPath);

        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}
//属性编辑
dmgis.olmap.ServiceLayer.prototype.GetBuildMapService = function (ActiveLayerName) {
    var dmBuildMapService = new dmgis.object.BuildServiceParam();
    dmBuildMapService.serverName = this.ImgMapService.serverName; //服务名称
    dmBuildMapService.strlayername = ActiveLayerName; //查询的图层
    ;
    return dmBuildMapService;
}
dmgis.olmap.ServiceLayer.prototype.SendBuildMapService = function (svr) {
    var self = this
    this.serviceurl = this.mapService
    var url = this.serviceurl + "/dms/GetBuildMap/" + svr.serverName + "?param=" + encodeURIComponent(svr.GetXmlString());
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }
            var dmGetBuild = new dmgis.service.GetBuildInfo(data);
            self.HandleBuildInfo(dmGetBuild);
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });
}


//----------------等值图ContourLayer----------------//
dmgis.olmap.ContourLayer = dmgis.olmap.ContourLayer ? dmgis.olmap.ContourLayer : {};
dmgis.olmap.ContourLayer = (function (layerName, mapService, options) {
    this.serverName = layerName;
    var options = options ? options : {};
    this.mapService = mapService;
    this.ContoursData = null;
    this.maxZoom = options.maxZoom ? options.maxZoom : 18;
    this.minZoom = options.minZoom ? options.minZoom : 0;
    this.opacity = options.opacity ? options.opacity : 1;
    this.projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    ol.layer.Image.call(this, options);
})
ol.inherits(dmgis.olmap.ContourLayer, ol.layer.Image);
dmgis.olmap.ContourLayer.prototype.UpdateContoursAtt = function (dataurl) {
    var obj = this;
    var url = this.mapService + "/pws/CallPlugin/service";
    var postdata = "methodName=contour&postdata=GetInterpolationWork|" + encodeURIComponent(dataurl);
    $.ajax({
        type: "POST",
        url: url,
        data: postdata,
        async: false,
        success: function (data) {
            if (data != "") {
                obj.ContoursData = data;
            }
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });
};
dmgis.olmap.ContourLayer.prototype.RefreshMap = function (zoom, mapsize, env) {
    ;
    var iLevel = zoom;
    var extent = ol.proj.transformExtent(env, 'EPSG:3857',"EPSG:4326");
    if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
        if(this.ContoursData == null) return;
        //var postdata = this.ContoursData + "|" + this.serverName + "|" + mapsize[1] + "|" + mapsize[0] + "|" + extent[0] + "," + (extent[1] - 33200) + "," + extent[2] + "," + (extent[3] - 33200) + "|1";
        var postdata = this.ContoursData + "|" + this.serverName + "|" + mapsize[1] + "|" + mapsize[0] + "|" + extent[0] + "," + extent[1] + "," + extent[2] + "," + extent[3] + "|1";
        var obj = this;
        var url = this.mapService + "/pws/CallPlugin/service";
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            data: "methodName=contour&postdata=GetContourPic|" + encodeURIComponent(postdata),
            success: function (data) {
                if (data != null && data != "") {
                    var imgurl = obj.mapService + "/res/pws/" + data;
                    var imagesource = new ol.source.ImageStatic({
                        url: imgurl,
                        projection: this.projection,
                        crossOrigin: "Anonymous",
                        imageExtent: env
                    });
                    obj.setSource(imagesource);
                }
            },
            error: function (e) {
                this.$message.error(e.status);
            }
        });
    }
}


//----------------数据点图层PointDataLayer----------------//
dmgis.olmap.PointDataLayer = dmgis.olmap.PointDataLayer ? dmgis.olmap.PointDataLayer : {};
dmgis.olmap.PointDataLayer = (function (layerName, mapDivId, map, zIndex, minLevel, maxLevel) {
    this.map = map;
    this.mapDiv = $("#" + mapDivId);
    $(".ol-viewport", this.mapDiv).append("<div id=" + layerName + " class='drawData' style='z-index:" + zIndex + "'></div>");
    $(".ol-viewport", this.mapDiv).append("<span class='tag' style='pointer-events: none'></span>"); //添加标记  默认顺序999999
    this.el = $("#" + layerName, this.mapDiv);
    this.PointsArr = []; //用于保存点类信息的数组
    this.DataTemplate = null;
    this.TagTemplate = null;
    this.IsRemoveOverlay = true; //是否移除叠加图层
    this.MinLevel = minLevel;
    this.MaxLevel = maxLevel;
    this.MouseEvent = "mouseover"; //标记所使用事件
    this.OverlayWidth = 100; //标记间隔
    this.Visible = true; //是否可见
    this.XmlHttp = null;
    this.coverflag = true;
})
//清空数据
dmgis.olmap.PointDataLayer.prototype.clear = function () {
    this.PointsArr = [];
    if (this.XmlHttp != null) {
        this.XmlHttp.abort();
        this.XmlHttp = null;
    }
};
dmgis.olmap.PointDataLayer.prototype.DptoSp = function (x, y) {
    return dmgis.tool.DptoSpOL(this.map, x, y);
}
//设置index
dmgis.olmap.PointDataLayer.prototype.setzIndex = function (index) {
    this.el.css("zIndex", index);
};
dmgis.olmap.PointDataLayer.prototype.AddLegend = function (data, lendTitle) {
    this.mapDiv.find("#legend").remove(); //移除图例
    if (data != undefined && data.length > 0) {
        var append = '<table id="legend">';
        append += '<tr><td colspan=2 style="font-weight: bold;">' + lendTitle + "</td></tr>";
        for (var i = data.length - 1; i >= 0; i--) {
            var color = dmgis.tool.transWin32ColorToHtml(data[i].elementColor); //利用Cesium自带的color类工具进行颜色转换，并设置透明度，将rgba颜色转换从css颜色
            append += '<tr><td style="width:60px;height:32px;background-color:' + color + '"></td><td>' + data[i].elementValue + "</td></tr>";
        }
        append += "</table>";
        this.mapDiv.append(append);
    }
}
dmgis.olmap.PointDataLayer.prototype.AddPoint = function (url, data, DataTemplate, TagTemplate, success) {
    this.PointsArr = [];
    this.removeTag();
    this.DataTemplate = DataTemplate;
    this.TagTemplate = TagTemplate;
    var DataObj = this;
    if (this.XmlHttp != null) {
        //终止jQuery的ajax请求
        this.XmlHttp.abort();
        this.XmlHttp = null;
    }
    this.XmlHttp = $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function (data) {
            //根据返回的结果的类型来判断调用那种方法
            if (data.result.length != undefined && data.result.length > 0) {
                if (data.result[0] instanceof Array) {
                    //第一个数据是数组
                    DataObj.PointsArr = eval(data.result[0]);
                    //添加图例 图例标题
                    // DataObj.AddLegend(data[1], data[2]);
                } else {
                    DataObj.PointsArr = eval(data.result);
                }
            }
            DataObj.Draw();
            this.XmlHttp = null;
            //请求成功执行参数 success方法
            if (success != undefined) {
                success(DataObj.PointsArr);
            }
        },
        error: function (e) {
            this.XmlHttp = null;
        }
    });
};

dmgis.olmap.PointDataLayer.prototype.AddSinglePoint = function (data, DataTemplate, TagTemplate, success) {
    this.PointsArr = [];
    this.removeTag();
    this.DataTemplate = DataTemplate;
    this.TagTemplate = TagTemplate;
    var DataObj = this;
    if (this.XmlHttp != null) {
        //终止jQuery的ajax请求
        this.XmlHttp.abort();
        this.XmlHttp = null;
    }
    DataObj.CacheData = data;
    DataObj.PointsArr = eval(data);
    DataObj.Draw();
    DataObj.XmlHttp = null;
    success(DataObj.PointsArr);
};
dmgis.olmap.PointDataLayer.prototype.IsInScreen = function (extent, x, y) {
    if (x < extent[0]) return false;
    if (x > extent[2]) return false;
    if (y < extent[1]) return false;
    if (y > extent[3]) return false;
    return true;
}
//绘制点方法
dmgis.olmap.PointDataLayer.prototype.Draw = function () {
    this.el.html("");
    if (this.Visible) {
        var iLevel = this.map.getView().getZoom();
        var extent = this.map.getView().calculateExtent(this.map.getSize());
        if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {

            var TempArr = [];
            if (this.PointsArr == null) {
                return;
            }
            for (var i = 0; i < this.PointsArr.length; i++) {
                //如果是经纬度坐标，需要处理成墨卡托
                if (this.PointsArr[i].lon < 180 && this.PointsArr[i].lon > -180) {
                    var newcood = ol.proj.transform([this.PointsArr[i].lon, this.PointsArr[i].lat], 'EPSG:4326', "EPSG:3857");
                    this.PointsArr[i].lon = newcood[0];
                    this.PointsArr[i].lat = newcood[1];
                }
                //遍历点集合
                if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {

                    var ScreenCoor = dmgis.tool.DptoSpOL(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
                    if (ScreenCoor == undefined) continue;
                    var num = TempArr.length;
                    var bXjFlag = false;

                    if (this.IsRemoveOverlay) {
                        for (var j = 0; j <= num - 1; j++) {
                            if (Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth && Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth) {
                                bXjFlag = true;
                                break;
                            }
                        }
                        if (bXjFlag) {
                            continue;
                        }
                    }
                    TempArr.push(ScreenCoor);
                    this.el.append(this.DataTemplate(this.PointsArr[i], this));
                    var TheDiv = this.el.children().last();
                    TheDiv.css("left", TheDiv.attr("left") - TheDiv.width() / 2 + "px");
                    TheDiv.css("top", TheDiv.attr("top") - TheDiv.height() / 2 + "px");
                    TheDiv.attr("index", i);
                    if (this.TagTemplate != undefined && this.TagTemplate != null) {
                        var obj = this;
                        if(this.coverflag){
                            TheDiv.mouseover(function (e) {
                                this.MouseEvent = "mouseover";
                                obj.ShowTag(obj.PointsArr[parseInt($(this).attr("index"))].lon, obj.PointsArr[parseInt($(this).attr("index"))].lat, $(this).attr("index"), e);
                            });
                            TheDiv.mouseout(function (e) {
                                this.MouseEvent = "mouseout";
                                obj.removeTag();
                            });
                        }
                        TheDiv.click(function (e) {
                            obj.ShowTag(obj.PointsArr[parseInt($(this).attr("index"))].lon, obj.PointsArr[parseInt($(this).attr("index"))].lat, $(this).attr("index"), e);
                        });
                    }
                }
            }
        }
    }
};
//移除标记
dmgis.olmap.PointDataLayer.prototype.removeTag = function () {
    $(".tag", this.mapDiv).html("");
};
dmgis.olmap.PointDataLayer.prototype.GetInWinCoor = function (x, y) {
    return new dmgis.object.Point(x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]), y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0]));
};
//显示Marker
dmgis.olmap.PointDataLayer.prototype.ShowTag = function (x, y, i, e) {
    $(".tag", this.mapDiv).html(this.TagTemplate(this.PointsArr[i], i));
    var InWinCoor = this.GetInWinCoor(e.clientX, e.clientY); //update
    var left = InWinCoor.x;
    var top = InWinCoor.y;

    if (this.MouseEvent == "mouseover") {
        if (InWinCoor.x < $(".tag", this.mapDiv).children().eq(0).width()) {
            left = 10;
        }
        if (InWinCoor.x > this.mapDiv.width() - $(".tag", this.mapDiv).children().eq(0).width()) {
            left = this.mapDiv.width() - $(".tag", this.mapDiv).children().eq(0).width() - 10;
        }
        if (InWinCoor.y > this.mapDiv.height() - $(".tag", this.mapDiv).children().eq(0).height()) {
            top = this.mapDiv.height() - $(".tag", this.mapDiv).children().eq(0).height() - 10;
        }
        $(".tag", this.mapDiv).css("left", left + "px");
        $(".tag", this.mapDiv).css("top", top + "px");
    } else {
        var MapCoor = dmgis.tool.DptoSpOL(this.map, x, y);
        $(".tag", this.mapDiv).attr("MapLeft", x);
        $(".tag", this.mapDiv).attr("MapTop", y);

        $(".tag", this.mapDiv).css("left", MapCoor.x + "px");
        $(".tag", this.mapDiv).css("top", MapCoor.y - $(".tag", this.mapDiv).height() + "px");
    }
};
dmgis.olmap.PointDataLayer.prototype.RefreshMap = function () {
    $(".tag", this.mapDiv).html("");
    if (this.Visible) {
        var iLevel = this.map.getView().getZoom();

        if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
            this.Draw();
        }
    }
}

//----------------网格点图层GridPointDataLayer----------------//
dmgis.olmap.GridPointDataLayer = dmgis.olmap.GridPointDataLayer ? dmgis.olmap.GridPointDataLayer : {};
dmgis.olmap.GridPointDataLayer = (function (layerName, mapDivId, map, zIndex, minLevel, maxLevel) {
    this.map = map;
    this.mapDiv = $("#" + mapDivId);
    $(".ol-viewport", this.mapDiv).append("<div id=" + layerName + " class='drawData' style='z-index:" + zIndex + "'></div>");
    $(".ol-viewport", this.mapDiv).append("<span class='tag' style='pointer-events: none'></span>"); //添加标记  默认顺序999999
    this.el = $("#" + layerName, this.mapDiv);
    this.PointsArr = []; //用于保存点类信息的数组
    this.DataTemplate = null;
    this.TagTemplate = null;
    this.IsRemoveOverlay = true; //是否移除叠加图层
    this.MinLevel = minLevel;
    this.MaxLevel = maxLevel;
    this.MouseEvent = "mouseover"; //标记所使用事件
    this.OverlayWidth = 100; //标记间隔
    this.Visible = true; //是否可见
    this.XmlHttp = null;
    this.GridCode = "";  //网格点
    this.GridRequestPar = null;
    this.BaseLV = 5; //默认级别
    this.Extent = null;
    this.Resolution = 0;
    this.tileSize = 256;
    this.IndexList = new Array();
})
//清空数据
dmgis.olmap.GridPointDataLayer.prototype.clear = function () {
    this.PointsArr = [];
    this.GridCode = "";
    this.GridRequestPar = null;
    if (this.XmlHttp != null) {
        this.XmlHttp.abort();
        this.XmlHttp = null;
    }
};
//设置index
dmgis.olmap.GridPointDataLayer.prototype.setzIndex = function (index) {
    this.el.css("zIndex", index);
};
//移除标记
dmgis.olmap.GridPointDataLayer.prototype.removeTag = function () {
    $(".tag", this.mapDiv).html("");
};
dmgis.olmap.GridPointDataLayer.prototype.GetInWinCoor = function (x, y) {
    return new dmgis.object.Point(x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]), y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0]));
};
dmgis.olmap.GridPointDataLayer.prototype.DptoSp = function (x, y) {
    return dmgis.tool.DptoSpOL(this.map, x, y);
}
dmgis.olmap.GridPointDataLayer.prototype.IsInScreen = function (extent, x, y) {
    if (x < extent[0]) return false;
    if (x > extent[2]) return false;
    if (y < extent[1]) return false;
    if (y > extent[3]) return false;
    return true;
}
//显示Marker
dmgis.olmap.GridPointDataLayer.prototype.ShowTag = function (x, y, i, e) {
    $(".tag", this.mapDiv).html(this.TagTemplate(this.PointsArr[i], i));
    var InWinCoor = this.GetInWinCoor(e.clientX, e.clientY); //update
    var left = InWinCoor.x;
    var top = InWinCoor.y;
    if (this.MouseEvent == "mouseover") {
        if (InWinCoor.x < $(".tag", this.mapDiv).children().eq(0).width()) {
            left = 10;
        }
        if (InWinCoor.x > this.mapDiv.width() - $(".tag", this.mapDiv).children().eq(0).width()) {
            left = this.mapDiv.width() - $(".tag", this.mapDiv).children().eq(0).width() - 10;
        }
        if (InWinCoor.y > this.mapDiv.height() - $(".tag", this.mapDiv).children().eq(0).height()) {
            top = this.mapDiv.height() - $(".tag", this.mapDiv).children().eq(0).height() - 10;
        }
        $(".tag", this.mapDiv).css("left", left + "px");
        $(".tag", this.mapDiv).css("top", top + "px");
    } else {
        var MapCoor = dmgis.tool.DptoSpOL(this.map, x, y);
        $(".tag", this.mapDiv).attr("MapLeft", x);
        $(".tag", this.mapDiv).attr("MapTop", y);

        $(".tag", this.mapDiv).css("left", MapCoor.x + "px");
        $(".tag", this.mapDiv).css("top", MapCoor.y - $(".tag", this.mapDiv).height() + "px");
    }
};
//获取在范围内网格的索引
dmgis.olmap.GridPointDataLayer.prototype.GetGridCode = function () {
    var extent = this.map.getView().calculateExtent(this.map.getSize());
    var rectmap = new dmgis.object.Envelope();
    rectmap.initextent(extent);//得到当前大小窗口地图的范围
    if (!dmgis.tool.Intersect(rectmap, this.Extent))
        return;
    var imgRowCount = Math.pow(2, this.BaseLV);
    var dx = (this.Extent.maxx - this.Extent.minx) / imgRowCount;
    var andrect = dmgis.tool.AndRect(rectmap, this.Extent);
    var startCol = Math.floor((andrect.minx - this.Extent.minx) / dx);//开始列
    var endCol = Math.floor((andrect.maxx - this.Extent.minx) / dx) + 1; //结束列
    var startRow = Math.floor((andrect.miny - this.Extent.miny) / dx); //开始行
    var endRow = Math.floor((andrect.maxy - this.Extent.miny) / dx) + 1; //结束行
    for (var i = startRow; i <= endRow; i++) {
        for (var j = startCol; j <= endCol; j++) {
            var code = i * this.tileSize + j;
            if (this.GridCode.indexOf("" + code) == -1) {
                this.GridCode += code + ",";
            }
        }
    }
    
};
//根据格网索引请求点  blv为编码网格，一般都为5;
dmgis.olmap.GridPointDataLayer.prototype.AddPoint = function (blv, extent, url, data, DataTemplate, TagTemplate, success) {
    this.BaseLV = blv;
    this.Extent = extent;
    this.Resolution = (extent.maxx - extent.minx) / Math.pow(2, blv) / this.tileSize;
    this.GridRequestPar = new dmgis.object.GridRequestPar(url, data, DataTemplate, TagTemplate, success); //GridRequestPar：Grid请求参数
    this.removeTag();
    var obj = this.map;
    this.DataTemplate = DataTemplate;
    this.TagTemplate = TagTemplate;
    var DataObj = this;
    if (this.XmlHttp != null) {
        this.XmlHttp.abort();
        this.XmlHttp = null;
    }
    this.GridCode = "";
    var res = this.map.getView().getResolution();//当前分辨率
    if (res <= this.Resolution) {
        this.GetGridCode();
    }

    if (this.GridCode != "") {
        this.GridCode = this.GridCode.substring(0, this.GridCode.length - 1);
        this.XmlHttp = $.ajax({
            type: "POST",
            url: url,
            data: {
                param: this.GridCode
            },
            success: function (data) {
                obj.XmlHttp = null;
                if (data.result == undefined)
                    return;
                DataObj.PointsArr = eval(data.result)
                if (success != undefined) {
                    success(DataObj.PointsArr);
                }
                DataObj.Draw();
            },
            error: function (e) {
                obj.XmlHttp = null;
            }
        });
        return true;
    } else {
        return false;
    }
};
dmgis.olmap.GridPointDataLayer.prototype.RefreshMap = function () {
    this.el.html('');
    if (this.Visible) {
        var iLevel = this.map.getView().getZoom();

        if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
            var res = this.map.getView().getResolution();//当前分辨率
            if (res > this.Resolution)
                return;
            this.AddPoint(this.BaseLV, this.Extent, this.GridRequestPar.url, this.GridRequestPar.data, this.GridRequestPar.DataTemplate, this.GridRequestPar.TagTemplate, this.GridRequestPar.success);
        }
    }
}
dmgis.olmap.GridPointDataLayer.prototype.Draw = function () {
    var TempArr = [];
    if (this.PointsArr == null) {
        return;
    }
    var extent = this.map.getView().calculateExtent(this.map.getSize());
    for (var i = 0; i < this.PointsArr.length; i++) {
        //如果是经纬度坐标，需要处理成墨卡托
        if (this.PointsArr[i].lon < 180 && this.PointsArr[i].lon > -180) {
            var newcood = ol.proj.transform([this.PointsArr[i].lon, this.PointsArr[i].lat], 'EPSG:4326', "EPSG:3857");
            this.PointsArr[i].lon = newcood[0];
            this.PointsArr[i].lat = newcood[1];
        }
        //遍历点集合
        if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {
            var ScreenCoor = dmgis.tool.DptoSpOL(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
            if (ScreenCoor == undefined) continue;
            var num = TempArr.length;
            var bXjFlag = false;

            if (this.IsRemoveOverlay) {
                for (var j = 0; j <= num - 1; j++) {
                    if (Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth && Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth) {
                        bXjFlag = true;
                        break;
                    }
                }
                if (bXjFlag) {
                    continue;
                }
            }
            TempArr.push(new dmgis.object.Point(ScreenCoor.x, ScreenCoor.y));
            this.el.append(this.DataTemplate(this.PointsArr[i], this));
            var TheDiv = this.el.children().last();
            TheDiv.css("left", TheDiv.attr("left") - TheDiv.width() / 2 + "px");
            TheDiv.css("top", TheDiv.attr("top") - TheDiv.height() / 2 + "px");
            TheDiv.attr("index", i);
            if (this.TagTemplate != undefined && this.TagTemplate != null) {
                var obj = this;
                TheDiv.mouseover(function (e) {
                    obj.MouseEvent == "mouseover";
                    obj.ShowTag(obj.PointsArr[parseInt($(this).attr("index"))].lon, obj.PointsArr[parseInt($(this).attr("index"))].lat, $(this).attr("index"), e);
                });
                TheDiv.mouseout(function (e) {
                    obj.MouseEvent == "mouseout";
                    e.preventDefault();
                    obj.removeTag();
                });
                TheDiv.click(function (e) {
                    obj.ShowTag(obj.PointsArr[parseInt($(this).attr("index"))].lon, obj.PointsArr[parseInt($(this).attr("index"))].lat, $(this).attr("index"), e);
                });
            }
        }
    }
};

//----------------ogc wmts----------------//
dmgis.olmap.OgcTileLayer = dmgis.olmap.OgcTileLayer ? dmgis.olmap.OgcTileLayer : {};
dmgis.olmap.OgcTileLayer = (function (layerName, mapService, tileType, options) {
    var layerName = layerName;
    var mapService = mapService;
    var tileType = tileType;//是否动态裁图
    var options = options ? options : {};
    var resolutions = [];
    var matrixIds = [];
    var minx = options.extent[0];
    var miny = options.extent[1];
    var maxx = options.extent[2];
    var maxy = options.extent[3];
    var projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    var tileSize = options.tileSize ? options.tileSize : 256;
    var maxZoom = options.maxZoom ? options.maxZoom : 18;
    var minZoom = options.minZoom ? options.minZoom : 1;
    // 计算百度使用的分辨率
    for (var i = 0; i <= maxZoom; i++) {
        resolutions[i] = (maxx - minx) / Math.pow(2, i) / tileSize;
        matrixIds[i] = i;
    }
    // var imgUrl = mapService + "/igs/ogc/tile/WMTSServer";
    // // WMTS
    // var source = new ol.source.WMTS({
    //     url: imgUrl,
    //     layer: layerName,
    //     matrixSet: 'EPSG:3857',
    //     format: 'image/jpeg',
    //     projection: projection,
    //     tileGrid: new ol.tilegrid.WMTS({
    //         origin: [minx, maxy],
    //         resolutions: resolutions,
    //         matrixIds: matrixIds,
    //     }),
    //     style: 'default',
    //     wrapX: false,
    // });

    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [minx, maxy], // 设置原点坐标
        resolutions: resolutions, // 设置分辨率
        tileSize: tileSize,
        minZoom: minZoom,
        maxZoom: maxZoom,
        extent: options.extent
    });
    var source = new ol.source.XYZ({
        extent: options.extent,
        tileGrid: tilegrid,
        maxZoom: maxZoom,
        minZoom: minZoom,
        projection: projection,
        tileUrlFunction: function (tileCoord) {
            ;
            if (tileType) {
                var z = tileCoord[0];
                var y = Math.pow(2, z) - 1 - (Math.abs(tileCoord[2]) - 1);
                var x = tileCoord[1];
                var imgUrl = mapService + "/igs/ogc/tile/WMTSServer?service=WMTS" +
                    "&request=GetTile&version=1.0.0&layer=" + layerName +
                    "&style=default&Format=image/png&tilematrixset=WholeWorld_CRS_84" +
                    "&TileMatrix={z}&TileRow={x}&TileCol={y}";
                return imgUrl.replace("{z}", z).replace("{x}", x).replace("{y}", y);
            } else {
                var z = tileCoord[0];
                var y = Math.pow(2, z) - 1 - (Math.abs(tileCoord[2]) - 1);
                var x = tileCoord[1];
                if (y > -1) {
                    var imgUrl = mapService + "/igs/ogc/tile/WMTSServer?service=WMTS" +
                        "&request=GetTile&version=1.0.0&layer=" + layerName +
                        "&style=default&Format=image/png&tilematrixset=WholeWorld_CRS_84" +
                        "&TileMatrix={z}&TileRow={y}&TileCol={x}";
                    return imgUrl.replace("{z}", z).replace("{x}", x).replace("{y}", y);
                }
            }


        }
    });
    var options = {
        title: layerName,
        source: source,
        wrapX: true
    };
    ol.layer.Tile.call(this, options);
})
ol.inherits(dmgis.olmap.OgcTileLayer, ol.layer.Tile);


//----------------ogc wms----------------//
dmgis.olmap.OgcwmsLayer = dmgis.olmap.OgcwmsLayer ? dmgis.olmap.OgcwmsLayer : {};
dmgis.olmap.OgcwmsLayer = (function (layerName, mapService, options) {
    this.serverName = layerName;
    var options = options ? options : {};
    this.mapService = mapService;
    this.maxZoom = options.maxZoom ? options.maxZoom : 18;
    this.minZoom = options.minZoom ? options.minZoom : 0;
    this.opacity = options.opacity ? options.opacity : 1;
    this.dprojection = options.projection;
    this.projection = options.projection ? ol.proj.get(options.projection) : ol.proj.get("EPSG:3857");
    this.ImgMapService = new dmgis.object.ImgServiceParam();
    ol.layer.Image.call(this, options);
})
ol.inherits(dmgis.olmap.OgcwmsLayer, ol.layer.Image);
dmgis.olmap.OgcwmsLayer.prototype.RefreshMap = function (ImgServiceParam, layname, zoom, type) {
    var iLevel = zoom;
    if (iLevel >= this.minZoom && iLevel <= this.maxZoom) {
        this.ImgMapService = ImgServiceParam;
        var extent = this.ImgMapService.DispRect;
        var url = "";
        if (type == "0") {
            url = this.mapService + "/igs/ogc/layer/" + this.serverName +
                "/WMSServer?request=GetMap&version=1.3.0&layers=" +
                layname + "&styles=default&crs=" + this.dprojection +
                "&bbox=" + extent.minx + "," + extent.miny + "," + extent.maxx + "," + extent.maxy +
                "&width=" + this.ImgMapService.imgWid + "&height=" + this.ImgMapService.imgHig + "&format=image/png";
        } else {
            url = this.mapService + "/igs/ogc/doc/layer/" + this.serverName +
                "/WMSServer?request=GetMap&version=1.3.0&layers=" +
                layname + "&styles=default&crs=" + this.dprojection +
                "&bbox=" + extent.minx + "," + extent.miny + "," + extent.maxx + "," + extent.maxy +
                "&width=" + this.ImgMapService.imgWid + "&height=" + this.ImgMapService.imgHig + "&format=image/png";
        }
        var imagesource = new ol.source.ImageStatic({
            url: url,
            projection: this.projection,
            crossOrigin: "Anonymous",
            imageExtent: [extent.minx, extent.miny, extent.maxx, extent.maxy]
        });
        this.setSource(imagesource);
    }
}
dmgis.olmap.OgcwmsLayer.prototype.GetImgSvrParam = function () {
    return this.ImgMapService;
}
//属性服务
dmgis.olmap.OgcwmsLayer.prototype.GetFeatureMapService = function (ActiveLayerName, serverName) {
    var dmFeatureMapService = new dmgis.object.FeatureServiceParam();
    dmFeatureMapService.serverName = serverName; //服务名称
    dmFeatureMapService.strlayername = ActiveLayerName;
    
    return dmFeatureMapService;
}
dmgis.olmap.OgcwmsLayer.prototype.SendFeatureMapService = function (svr, map, coordinate, type) {
    var self = this
    this.serviceurl = this.mapService
    var extent = this.ImgMapService.DispRect;

    var ScreenCoor = dmgis.tool.DptoSpOL(map, coordinate[0], coordinate[1]);
    var I = parseInt(ScreenCoor.x);
    var J = parseInt(ScreenCoor.y);
    
    

    var url = "";
    if (type == "0") {
        url = this.serviceurl + "/igs/ogc/layer/" + svr.serverName +
            "/WMSServer?request=GetFeatureInfo&version=1.3.0&layers=" + svr.strlayername +
            "&styles=default&crs=" + this.dprojection + "&bbox=" + extent.minx + "," + extent.miny + "," + extent.maxx + "," + extent.maxy +
            "&width=" + this.ImgMapService.imgWid + "&height=" + this.ImgMapService.imgHig +
            "&format=text/xml&query_Layers=" + svr.strlayername + "&info_format=text/xml" +
            "&I=" + I + "&J=" + J + "";
    } else {
        url = this.mapService + "/igs/ogc/doc/layer/" + svr.serverName +
            "/WMSServer?request=GetFeatureInfo&version=1.3.0&layers=" + svr.strlayername +
            "&styles=default&crs=" + this.dprojection + "&bbox=" + extent.minx + "," + extent.miny + "," + extent.maxx + "," + extent.maxy +
            "&width=" + this.ImgMapService.imgWid + "&height=" + this.ImgMapService.imgHig +
            "&format=text/xml&query_Layers=" + svr.strlayername + "&info_format=text/xml" +
            "&I=" + I + "&J=" + J + "";
    }
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }
            // ;
            var dmGetFeature = new dmgis.service.GetWMSFeatureInfo(data);
            ;
            self.HandleFeatureInfo(dmGetFeature);
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}

//----------------ogc wmf----------------//
dmgis.olmap.OgcwfsLayer = dmgis.olmap.OgcwfsLayer ? dmgis.olmap.OgcwfsLayer : {};
dmgis.olmap.OgcwfsLayer = (function (layerName, mapService) {
    this.serverName = layerName;
    this.mapService = mapService;
})
dmgis.olmap.OgcwfsLayer.prototype.GetFeatureMapService = function (ActiveLayerName, serverName) {
    var dmFeatureMapService = new dmgis.object.FeatureServiceParam();
    dmFeatureMapService.serverName = serverName; //服务名称
    dmFeatureMapService.strlayername = ActiveLayerName;
    
    return dmFeatureMapService;
}
dmgis.olmap.OgcwfsLayer.prototype.SendDescribeFeatureTypeMapService = function (svr, type) {
    var self = this
    this.serviceurl = this.mapService

    var url = "";
    if (type == "0") {
        url = this.serviceurl + "/igs/ogc/layer/" + svr.serverName +
            "/WFSServer?request=DescribeFeatureType&version=1.1.0&service=WFS&typename=" + svr.strlayername;
    } else {
        url = this.serviceurl + "/igs/ogc/doc/layer/" + svr.serverName +
            "/WFSServer?request=DescribeFeatureType&version=1.1.0&service=WFS&typename=" + svr.strlayername;
    }
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }
            // ;
            var dmGetFeature = new dmgis.service.GetWFSDescribeFeatureInfo(data);
            ;
            self.HandleFeatureInfo(dmGetFeature);
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}

dmgis.olmap.OgcwfsLayer.prototype.SendGetFeatureMapService = function (svr, extent, dprojection, type) {
    var self = this
    this.serviceurl = this.mapService

    var url = "";
    if (type == "0") {
        url = this.serviceurl + "/igs/ogc/layer/" + svr.serverName +
            "/WFSServer?request=GetFeature&version=1.1.0&service=WFS&typename=" + svr.serverName + ":" + svr.strlayername +
            "&bbox=" + extent[0] + "," + extent[1] + "," + extent[2] + "," + extent[3] + "," + dprojection;
    } else {
        url = this.serviceurl + "/igs/ogc/doc/layer/" + svr.serverName +
            "/WFSServer?request=GetFeature&version=1.1.0&service=WFS&typename=" + svr.serverName + ":" + svr.strlayername +
            "&bbox=" + extent[0] + "," + extent[1] + "," + extent[2] + "," + extent[3] + "," + dprojection;
    }
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            if (data == "服务请求异常!") {
                this.$message.error("服务请求异常!");
                return;
            }
            // ;
            var dmGetFeature = new dmgis.service.GetWFSFeatureInfo(data, svr.serverName + ":" + svr.strlayername);
            ;
            self.HandleFeatureInfo(dmGetFeature);
        },
        error: function (e) {
            this.$message.error(e.status);
        }
    });

}

//----------------地图操作基本方法----------------//
dmgis.olmap.Tools = dmgis.olmap.Tools ? dmgis.olmap.Tools : {};
dmgis.olmap.Tools = (function (map, _extent) {
    this.map = map;
    this.dpi = 10;
    this.viewport = map.getViewport(); //地图页面元素
    this.overLayers = [];
    this.MouseState = 0; //鼠标状态默认移动
    this.MouseFlag = false; //用于判断鼠标是否停止移动
    this.snap = null; //修改类别
    this.modify = null; //修改操作类
    this.listener = null; //绘图过程中的事件监听
    this.drawSource = null; //当前绘制源
    this.measureTooltip = null; // 一个覆盖面来显示测量对象, ol类型 {ol.Overlay}
    this.measureTooltipElement = null; //测量提示对象
    this.helpTooltip = null; //  * 一个覆盖面来显示帮助对象,ol类型 {ol.Overlay}
    this.helpTooltipElement = null; //帮助提示对象
    this.draw = null; //交互操作中绘制类
    this.drawStyle = null; //绘制样式
    this.vlaystyle = null; //矢量数组对应的显示参数
    this.mapExtent = _extent; //地图显示范围
    this.modify = null; //修改操作类
    this.vectorLayers = {}; //矢量图层
    this.activeVctLayer = null; //当前激活图层
    this.sketch = null; //
    this.BindEvents();

    this.callback = null;
})
//事件绑定
dmgis.olmap.Tools.prototype.BindEvents = function (_mousesstate) {
    //移动事件绑定
    var dmgismap = this;
    //dmgismap.map.on("postrender", dmgismap.render, dmgismap);
    dmgismap.map.on('pointermove', dmgismap.pointerMoveHandler, this); //将地图对象传送到ol.map中
    //点击事件绑定
    //dmgismap.map.on('singleclick', dmgismap.singleClick, this); //真实单个点击
    //由于openlayer没有监听右键菜单,采用地图容器html元素类来实现操作,这里次啊用jQuery中的on方法来添加事件监听,同时也可以用off方法来关闭事件监听
    $(this.viewport).on("contextmenu", dmgismap, dmgismap.contextmenu);
};

//右键菜单重定义
dmgis.olmap.Tools.prototype.contextmenu = function (evt) {
    var dmgismap = evt.data;
    dmgismap.MouseFlag = false;
    if (dmgismap.helpTooltipElement) {
        dmgismap.helpTooltipElement.innerHTML = "";
    }
    dmgismap.map.removeInteraction(dmgismap.draw) //移除绘制控制
    evt.preventDefault(); //屏蔽自带的右键事件
    if(dmgismap.MouseState == 9) {
        dmgismap.MouseState = -1;
        return;
    }
    var coordinate = dmgismap.map.getEventCoordinate(evt);
    var overlay = dmgismap.map.getOverlayById("menuCotent"); //id唯一,且不改变
    overlay.setPosition(coordinate);
    $('.MapMenu', overlay.element).css("display", "block");
    dmgismap.SwitchMouseState(0);
};

//添加覆盖层
dmgis.olmap.Tools.prototype.AddOverlayer = function (overLay) {
    this.overLayers.push(overLay);
    this.map.addOverlay(overLay);
};
dmgis.olmap.Tools.prototype.clearAll= function (){
    //删除矢量图层数据
    for (var obj in this.vectorLayers) {
        if (!obj.includes("border")) {
            this.vectorLayers[obj].getSource().clear(true);
        }
    }
    //删除覆盖层数据
    for (i = 0; i < this.overLayers.length; i++) {
        var overLay = this.overLayers[i];
        //避免删除右键菜单
        if (overLay.getId() !== "menuCotent") {
            overLay.element.remove(); //有问题
        }
    }
}
//复位
dmgis.olmap.Tools.prototype.Reset = function () {
    this.fitExtent(this.mapExtent);
};
//自适应地图范围
dmgis.olmap.Tools.prototype.fitExtent = function (_extent) {
    if (_extent === undefined) {
        _extent = this.mapExtent;
    }
    this.map.getView().fit(_extent);
};

/**
 * 创建一个帮助提示
 */
dmgis.olmap.Tools.prototype.createHelpTooltip = function () {
    if (this.helpTooltipElement) {
        this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement);
    }
    this.helpTooltipElement = document.createElement('div');
    this.helpTooltipElement.className = 'tooltip hidden';
    this.helpTooltip = new ol.Overlay({
        element: this.helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    this.AddOverlayer(this.helpTooltip);
};
/**
 * 创建一个测量提示
 */
dmgis.olmap.Tools.prototype.createMeasureTooltip = function () {
    if (this.measureTooltipElement) {
        this.measureTooltipElement.parentNode.removeChild(this.measureTooltipElement);
    }
    this.measureTooltipElement = document.createElement('div');
    this.measureTooltipElement.className = 'tooltip tooltip-measure';
    this.measureTooltip = new ol.Overlay({
        element: this.measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center'
    });
    this.AddOverlayer(this.measureTooltip);
};

//移动操作
dmgis.olmap.Tools.prototype.pointerMoveHandler = function (evt) {
    if (this.MouseState === 4 || this.MouseState === 5) {
        /** @type {string} */
        var helpMsg = '点击地图以开始绘制';

        var continuePolygonMsg = '点击地图绘制多边形';
        /**
         * Message to show when the user is drawing a line.
         * @type {string}
         */
        var continueLineMsg = '点击地图绘制线';
        if (this.sketch) {
            var geom = (this.sketch.getGeometry());
            if (geom instanceof ol.geom.Polygon) {
                helpMsg = continuePolygonMsg;
            } else if (geom instanceof ol.geom.LineString) {
                helpMsg = continueLineMsg;
            }
        }

        this.helpTooltipElement.innerHTML = helpMsg;
        this.helpTooltip.setPosition(evt.coordinate);
        this.helpTooltipElement.classList.remove('hidden');
        this.map.getViewport().addEventListener('mouseout', function () {
            dmgismap.helpTooltipElement.classList.add('hidden');
        });
    }
};

//移动事件
dmgis.olmap.Tools.prototype.drawstart = function (evt) {
    var dmgismap = this;
    var e = evt.originalEvent; //
    //鼠标停止移动
    if (!this.MouseFlag) {
        return;
    }
    switch (this.MouseState) {
        case 4:
        case 5: {
            // set sketch
            dmgismap.sketch = evt.feature;
            /** @type {ol.Coordinate|undefined} */
            var tooltipCoord = evt.coordinate;

            listener = dmgismap.sketch.getGeometry().on('change', function (evt) {
                var geom = evt.target;
                var output;
                if (geom instanceof ol.geom.Polygon) {
                    output = dmgismap.formatArea(geom);
                    tooltipCoord = geom.getInteriorPoint().getCoordinates();
                } else if (geom instanceof ol.geom.LineString) {
                    output = dmgismap.formatLength(geom);
                    tooltipCoord = geom.getLastCoordinate();
                }
                dmgismap.measureTooltipElement.innerHTML = output;
                dmgismap.measureTooltip.setPosition(tooltipCoord);
            });
        }
            break;
        default:
            dmgismap.sketch = evt.feature;
            break;
    }
};

//移动结束事件
dmgis.olmap.Tools.prototype.drawend = function (evt) {
    var dmgismap = this;
    switch (this.MouseState) {
        case 4:
        case 5: {
            var dmgismap = this;
            dmgismap.measureTooltipElement.className = 'tooltip tooltip-static';
            dmgismap.measureTooltip.setOffset([0, -7]);
            //修改绘制的实体样式
            dmgismap.sketch.setStyle(dmgismap.vlaystyle);
            // unset sketch
            dmgismap.sketch = null;
            // unset tooltip so that a new one can be created
            dmgismap.measureTooltipElement = null;
            dmgismap.createMeasureTooltip();
            ol.Observable.unByKey(listener); //解除事件监听
        }
            break;
        case 8: {
            var dmgismap = this;
            dmgismap.sketch.setStyle(dmgismap.vlaystyle);
            // unset sketch
            dmgismap.sketch = null;
            if (evt.feature) {
                // 获取框选范围
                var geometry = evt.feature.getGeometry();
                var extent = geometry.getExtent();
                this.callback(extent)
            }
        }
            break;
        case 9: {
            var dmgismap = this;
            dmgismap.sketch.setStyle(dmgismap.vlaystyle);
            // unset sketch
            dmgismap.sketch = null;

            if (evt.feature) {
                var geometry = evt.feature.getGeometry();
                var extent = geometry.getExtent();
                var cliclpnts = geometry.flatCoordinates;
                this.callback(cliclpnts)
            }
        }
            break;
        default: {
            dmgismap.sketch.setStyle(dmgismap.vlaystyle);
            // unset sketch
            dmgismap.sketch = null;
        }
            break;
    }
};

/*
 *格式化长度输出.
 * @参数 {ol.geom.LineString} line The line.
 * @返回格式化的string类型长度.
 */
dmgis.olmap.Tools.prototype.formatLength = function (line) {
    var length = ol.Sphere.getLength(line);
    var output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
            ' ' + 'km';
    } else {
        output = (Math.round(length * 100) / 100) +
            ' ' + 'm';
    }
    return output;
};
/*
 *格式化面积输出.
 * @参数 {ol.geom.Polygon} polygon The polygon.
 * @返回格式化的string类型面积.
 */
dmgis.olmap.Tools.prototype.formatArea = function (polygon) {
    var area = ol.Sphere.getArea(polygon);
    var output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
    } else {
        output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
    }
    return output;
};

//添加绘制操作,soure为添加交互的矢量图层
dmgis.olmap.Tools.prototype.AddInteraction = function (_type, _source) {
    var dmgismap = this; //定义一个地图变量指向当前地图
    if (this.modify) {
        this.modify.setActive(false); //移除修改操作
    }
    switch (this.MouseState) {
        case 4:
        case 5: { //area为面积
            var type = (_type === 'area' ? 'Polygon' : 'LineString');
            //定义绘制的交互类型和相关参数
            dmgismap.draw = new ol.interaction.Draw({
                source: _source,
                type: type,
                style: new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: 'rgba(0, 0, 0, 0.5)',
                        lineDash: [10, 10],
                        width: 2
                    }),
                    image: new ol.style.Circle({
                        radius: 5,
                        stroke: new ol.style.Stroke({
                            color: 'rgba(0, 0, 0, 0.7)'
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(255, 255, 255, 0.2)'
                        })
                    })
                })
            });
            var style = new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: '#ffcc33',
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 7,
                    fill: new ol.style.Fill({
                        color: '#ffcc33'
                    })
                })
            });
            dmgismap.vlaystyle = style; //赋值
            dmgismap.drawStyle = dmgismap.draw.style_;
            dmgismap.activeVctLayer.setStyle(style); //激活图层
            dmgismap.map.addInteraction(dmgismap.draw) //添加绘制类到交互操作容器中
            //创建测量工具，这里需要再次封装
            dmgismap.createMeasureTooltip();
            dmgismap.createHelpTooltip();
            //绘制开始事件
            dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
            //绘制结束事件
            dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
        }
            break;
        case 6:
        case 7:
        case 9:
        case 10: {
            dmgismap.map.removeInteraction(dmgismap.draw);
            dmgismap.draw = new ol.interaction.Draw({
                source: _source,
                type: _type,
                style: dmgismap.drawStyle === null ? new ol.style.Style() : dmgismap.drawStyle
            });
            if (dmgismap.vlaystyle !== null) {
                dmgismap.activeVctLayer.setStyle(dmgismap.vlaystyle); //激活图层
            }
            dmgismap.map.addInteraction(dmgismap.draw);
            dmgismap.snap = new ol.interaction.Snap({
                source: _source
            });
            dmgismap.map.addInteraction(dmgismap.snap);
            //绘制开始事件
            dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
            //绘制结束事件
            dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
        }
            break;
        case 8: // 形状绘制
        {
            var value = "Box";
            if (value !== 'None') {
                var geometryFunction;
                if (value === 'Square') {
                    value = 'Circle';
                    geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
                } else if (value === 'Box') {
                    value = 'Circle';
                    geometryFunction = ol.interaction.Draw.createBox();
                } else if (value === 'Star') {
                    value = 'Circle';
                    geometryFunction = function (coordinates, geometry) {
                        if (!geometry) {
                            geometry = new ol.geom.Polygon(null);
                        }
                        var center = coordinates[0];
                        var last = coordinates[1];
                        var dx = center[0] - last[0];
                        var dy = center[1] - last[1];
                        var radius = Math.sqrt(dx * dx + dy * dy);
                        var rotation = Math.atan2(dy, dx);
                        var newCoordinates = [];
                        var numPoints = 12;
                        for (var i = 0; i < numPoints; ++i) {
                            var angle = rotation + i * 2 * Math.PI / numPoints;
                            var fraction = i % 2 === 0 ? 1 : 0.5;
                            var offsetX = radius * fraction * Math.cos(angle);
                            var offsetY = radius * fraction * Math.sin(angle);
                            newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
                        }
                        newCoordinates.push(newCoordinates[0].slice());
                        geometry.setCoordinates([newCoordinates]);
                        return geometry;
                    };
                }
                dmgismap.draw = new ol.interaction.Draw({
                    source: _source,
                    type: value,
                    style: dmgismap.drawStyle === null ? new ol.style.Style() : dmgismap.drawStyle,
                    geometryFunction: geometryFunction
                });

                dmgismap.map.addInteraction(dmgismap.draw);
                dmgismap.snap = new ol.interaction.Snap({
                    source: _source
                });
                dmgismap.map.addInteraction(dmgismap.snap);
                //绘制开始事件
                dmgismap.draw.on('drawstart', dmgismap.drawstart, dmgismap);
                //绘制结束事件
                dmgismap.draw.on('drawend', dmgismap.drawend, dmgismap);
            }
        }
            break;
        default:
            break;
    }
    dmgismap.MouseFlag = true;

};

//添加矢量绘制图层
dmgis.olmap.Tools.prototype.AddVectorLayer = function (sourse, vectorLayer) {
    var vector = new ol.layer.Vector({
        source: sourse,
        //设置图层的顺序 值越大图层在越上面
        zIndex: 99999
    });
    this.drawSource = sourse;
    this.vectorLayers[vectorLayer] = vector;
    this.map.addLayer(vector);
    this.activeVctLayer = vector; //设置当前激活图层
};

//设置激活矢量图层
dmgis.olmap.Tools.prototype.SetActiveVecLayer = function (vector) {
    this.activeVctLayer = vector; //设置激活矢量图层
    this.drawSource = vector.getSource(); //设置当前绘制数据源
};

//设置鼠标状态
dmgis.olmap.Tools.prototype.SwitchMouseState = function (state) {
    if (this.MouseFlag) {
        this.MouseFlag = !this.MouseFlag;
    }
    this.MouseState = state;
    this.SetActiveVecLayer(this.vectorLayers["vector"]);
    //0:移动，1放大，2:缩小，3:无，4：测量，5:点，6：线，7：矩形：8：多边形，9:圆
    var cursorArray = new Array('dmMapSource/image/openhand.cur', 'dmMapSource/image/ZoomIn.cur', 'dmMapSource/image/ZoomOut.cur', '', 'dmMapSource/image/ruler.cur', 'dmMapSource/image/PointQuery.cur', 'dmMapSource/image/LineQuery.cur', 'dmMapSource/image/RectQuery.cur', 'dmMapSource/image/PolygonQuery.cur', 'dmMapSource/image/CircleQuery.cur');
    this.MouseFlag = false;
    if (this.helpTooltipElement) {
        this.helpTooltipElement.innerHTML = "";
    }
    this.map.removeInteraction(this.draw); //移除绘制控制
    switch (state) {
        case -1: { //清空
            this.clearAll();
        }
            break;
        case 3: { //复位
            this.Reset();
            $(this.viewport).css("cursor", "url('" + cursorArray[3] + "'),default");
        }
            break;
        case 4: { //测距离
            this.AddInteraction("line", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[4] + "'),default");
        }
            break;
        case 5: { //侧面积
            this.AddInteraction("area", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[4] + "'),default");
        }
            break;
        case 6: //画点
        {
            this.AddInteraction("Point", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[5] + "'),default");
        }
            break;
        case 7: //线
        {
            this.AddInteraction("LineString", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[6] + "'),default");
        }
            break;
        case 8: //矩形
        {
            this.AddInteraction("Box", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[7] + "'),default");
        }
            break;
        case 9: //多边形
        {
            this.AddInteraction("Polygon", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[8] + "'),default");
        }
            break;
        case 10: //圆
        {
            this.AddInteraction("Circle", this.drawSource);
            $(this.viewport).css("cursor", "url('" + cursorArray[9] + "'),default");
        }
            break;
        default: { //其他
            $(this.viewport).css("cursor", "url('" + cursorArray[state] + "'),default");
        }
            break;
    }
};

//地图指北针
dmgis.olmap.Tools.prototype.AddCompass = function () {
    var CompassHTML = '<div class="CompassMain"><div class="Compass">' +
        '<div class="DMap_panN" title="向上平移"></div>' +
        '<div class="DMap_panW" title="向左平移"></div>' +
        '<div class="DMap_panE" title="向右平移"></div>' +
        '<div class="DMap_panS" title="向下平移"></div>' +
        '</div></div>';
    if ($(".CompassMain", $(this.viewport)).length === 0) {
        $(this.viewport).append(CompassHTML);
        var obj = this;
        $(".CompassMain .DMap_panN", $(this.viewport)).click(function () {
            obj.moveToUp();
            return false;
        });
        $(".CompassMain .DMap_panW", $(this.viewport)).click(function () {
            obj.moveToLeft();
            return false;
        });
        $(".CompassMain .DMap_panE", $(this.viewport)).click(function () {
            obj.moveToRight();
            return false;
        });
        $(".CompassMain .DMap_panS", $(this.viewport)).click(function () {
            obj.moveToDown();
            return false;
        });
    }
};

// 向左移动地图
dmgis.olmap.Tools.prototype.moveToLeft = function () {
    var mapCenter = this.map.getView().getCenter();
    var resolution = this.map.getView().getResolution(); //当前图层分辨率,
    mapCenter[0] += resolution * this.dpi; //每次移动10个像素
    this.map.getView().setCenter(mapCenter);
};

// 向右移动地图
dmgis.olmap.Tools.prototype.moveToRight = function () {
    var mapCenter = this.map.getView().getCenter();
    // 让地图中心的x值减少，即可使得地图向右移动，减少的值根据效果可自由设定
    var resolution = this.map.getView().getResolution(); //当前图层分辨率,
    mapCenter[0] -= resolution * this.dpi;
    this.map.getView().setCenter(mapCenter);
};

// 向上移动地图
dmgis.olmap.Tools.prototype.moveToUp = function () {
    var mapCenter = this.map.getView().getCenter();
    var resolution = this.map.getView().getResolution(); //当前图层分辨率,
    mapCenter[1] -= resolution * this.dpi;
    this.map.getView().setCenter(mapCenter);
};

// 向下移动地图
dmgis.olmap.Tools.prototype.moveToDown = function () {
    var mapCenter = this.map.getView().getCenter();
    var resolution = this.map.getView().getResolution(); //当前图层分辨率,
    mapCenter[1] += resolution * this.dpi;
    this.map.getView().setCenter(mapCenter);
};

// 放大地图
dmgis.olmap.Tools.prototype.zoomIn = function () {
    // 让地图的zoom增加1，从而实现地图放大
    this.map.getView().setZoom(this.map.getView().getZoom() + 1);
};

// 缩小地图
dmgis.olmap.Tools.prototype.zoomOut = function () {
    // 让地图的zoom减小1，从而实现地图缩小
    this.map.getView().setZoom(this.map.getView().getZoom() - 1);
};
//添加右键菜单
dmgis.olmap.Tools.prototype.AddRightMenu = function () {
    var meunHTML = '<ul class="MapMenu">' +
        '<li><a href="javascript:void(0);"><span class="bigIco"></span>放大</a></li>' +
        '<li><a href="javascript:void(0);"><span class="smallIco"></span>缩小</a></li>' +
        '<li><a href="javascript:void(0);"><span class="moveIco"></span>移动</a></li>' +
        '<li><a href="javascript:void(0);"><span class="pointIco"></span>复位</a></li>' +
        '<li><a href="javascript:void(0);"><span class="clearIco"></span>清空</a></li>' +
        '</ul>';
    //添加overLay,避免二次添加;
    if (this.map.getOverlayById("menuCotent")) {
        return;
    }
    var menu_overlay = new ol.Overlay({
        id: "menuCotent",
        element: $(meunHTML).get(0),
        positioning: 'center-center'
    });
    this.AddOverlayer(menu_overlay);
    var obj = this;
    $(".MapMenu a", $(this.viewport)).eq(0).click(function () {
        obj.SwitchMouseState(1);
        obj.zoomIn();
        $(".MapMenu", obj.viewport).css("display", "none");
        return false;
    });
    $(".MapMenu a", $(this.viewport)).eq(1).click(function () {
        obj.SwitchMouseState(2);
        obj.zoomOut();
        $(".MapMenu", obj.viewport).css("display", "none");
        return false;
    });
    $(".MapMenu a", $(this.viewport)).eq(2).click(function () {
        obj.SwitchMouseState(0);
        $(".MapMenu", obj.viewport).css("display", "none");
        return false;
    });
    $(".MapMenu a", $(this.viewport)).eq(3).click(function () {
        obj.SwitchMouseState(3);
        $(".MapMenu", obj.viewport).css("display", "none");
        return false;
    });
    $(".MapMenu a", $(this.viewport)).eq(4).click(function () {
        obj.SwitchMouseState(-1);
        $(".MapMenu", obj.viewport).css("display", "none");
        return false;
    });
};

//添加工具条
dmgis.olmap.Tools.prototype.AddToolMenu = function () {
    var that = this;
    var toolHtml = '<div class="tool-container">' +
        '<ul class="ul">' +
        '<a id="zoomin"><li><img class="img" alt="放大" title="放大"  src="dmMapSource/image/放大.png" /></li></a>' +
        '<a id="zoomout"><li><img class="img" alt="缩小" title="缩小"  src="dmMapSource/image/缩小.png"></li></a>' +
        '<a id="meslength"><li><img class="img" alt="测距" title="测距"  src="dmMapSource/image/测距.png"></li></a>' +
        '<a id="mesarea"><li><img class="img" alt="测面积" title="测面积"  src="dmMapSource/image/测面积.png"></li></a>' +
        '<a id="location"><li><img class="img" alt="定位" title="定位"  src="dmMapSource/image/定位.png"/></li></a>' +
        '<a style="display: none;" id="mapChange"><li><img class="img" alt="切换" title="切换" src="dmMapSource/image/切换.png"/></li></a>' +
        '<a id="tools"><li style="border-right:none;"><img class="img" alt="工具条" title="工具条" src="dmMapSource/image/工具条.png" /></li></a>' +
        '</ul></div>';
    var toolMap = ' <ul class="subtool hidden" id="mapType"> <li>基础</li><li>地形</li></ul>';
    if ($(".tool-container", $(this.viewport)).length === 0) {
        $(this.viewport).append(toolHtml);
        if ($("mapType", $(this.viewport)).length === 0) {
            $(".ol-viewport", this.mapdiv).append(toolMap); //添加地图类型切换工具
        }
        //添加鼠标悬停事件
        var $img = $(".tool-container a", $(this.viewport)).find("img");
        $img.on("mouseover", function () {
            $(this).attr("src", "dmMapSource/image/" + $(this).attr("title") + "1.png");
        });
        $img.on("mouseleave", function () {
            $(this).attr("src", "dmMapSource/image/" + $(this).attr("title") + ".png");
        });
        var dmgismap = this;

        $("#zoomin", $(this.viewport)).on("click", function () {
            dmgismap.SwitchMouseState(1);
            dmgismap.zoomIn();
        }); //放大
        $("#zoomout", $(this.viewport)).on("click", function () {
            dmgismap.SwitchMouseState(2);
            dmgismap.zoomOut();
        }); //缩小
        $("#meslength", $(this.viewport)).on("click", function () {
            dmgismap.SwitchMouseState(4);
        }); //测距
        $("#mesarea", $(this.viewport)).on("click", function () {
            dmgismap.SwitchMouseState(5);
        }); //测面积
        $("#location", $(this.viewport)).on("click", function () {
            dmgismap.SwitchMouseState(3);
        }); //定位
        $("#mapChange", $(this.viewport)).on("click", function () {
            if ($(".subtool", $(this.viewport)).hasClass("hidden")) {
                var top = $(".tool-container").height() + $(".tool-container").get(0).offsetTop;
                var left = $(".tool-container").get(0).offsetLeft + ($(this).index()) * $(".tool-container a").width();
                $(".subtool", $(this.viewport)).css("top", top);
                $(".subtool", $(this.viewport)).css("left", left);
                $(".subtool", $(this.viewport)).removeClass("hidden");
            } else {
                $(".subtool", $(this.viewport)).addClass("hidden");
            }
        }); //切换
        $("#tools", $(this.viewport)).on("click", function () { //判断是否显示
            if ($(this).siblings().hasClass("hidden")) {
                $(this).siblings().removeClass("hidden");
            } else {
                $(this).siblings().addClass("hidden");
            }
        });

    }
};

//颜色转换
dmgis.olmap.Tools.prototype.transWin32ColorToHtml = function (color) {
    var htmlColor = "#ffffff";
    color = parseInt(color);
    try {
        var r = (color & 255).toString(16);
        var g = (color >> 8 & 255).toString(16);
        var b = (color >> 16 & 255).toString(16);
        htmlColor = "#" + (r.length < 2 ? ("0" + r) : r) + (g.length < 2 ? ("0" + g) : g) + (b.length < 2 ? ("0" + b) : b);
    } catch (e) {
        // TODO: handle exception
        this.$message.error(e.message);
        this.$message.error(e.message);
    }
    return htmlColor;
};

// 加载线
dmgis.olmap.Tools.prototype.drawLine = function (entites) {
    if (entites !== null && entites.length > 0) {
        for (var i = 0; i < entites.length; i++) {
            var coordinates = new Array(); //先声明一维
            for (var j = 0; j < entites[i].posArr.length; j++) {
                coordinates[j] = new Array(); //再声明二维
                for (var k = 0; k < 2; k += 2) {
                    coordinates[j][k] = entites[i].posArr[j].x;
                    coordinates[j][k + 1] = entites[i].posArr[j].y;
                }
            }
            //声明一个新的数组
            var coordinatesPolygon = new Array();
            //循环遍历将经纬度转到"EPSG:3857"投影坐标系下
            for (var t = 0; t < coordinates.length; t++) {
                var pointTransform = ol.proj.transform([coordinates[t][0], coordinates[t][1]], 'EPSG:4326', 'EPSG:3857');
                coordinatesPolygon.push(pointTransform);
            }
            var source = new ol.source.Vector();
            var geom = new ol.geom.LineString(coordinatesPolygon);
            //多边形要素类
            var feature = new ol.Feature({
                geometry: geom,
                ROADNAME: entites[i].ROADNAME,
                PAVEMENT: entites[i].PAVEMENT,
                MATERIAL: entites[i].MATERIAL
            });
            var lineStyle = new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: this.transWin32ColorToHtml(entites[i].color == undefined ? 65535 : entites[i].color).replace(/\"/g, "'"),
                    width: 2
                })
            });
            feature.setStyle(lineStyle);
            source.addFeature(feature);
            this.AddVectorLayer(source, "Traline" + i);
        }
    }
    //this.fitExtent();
};

dmgis.olmap.Tools.prototype.ContainsPoint = function (polygon, pointX, pointY) {
    let n = polygon.length >> 1;

    let ax, lup;
    let ay = polygon[2 * n - 3] - pointY;
    let bx = polygon[2 * n - 2] - pointX;
    let by = polygon[2 * n - 1] - pointY;

    if (bx === 0 && by === 0) return false; // point on edge

    // let lup = by > ay;
    for (let ii = 0; ii < n; ii++) {
        ax = bx;
        ay = by;
        bx = polygon[2 * ii] - pointX;
        by = polygon[2 * ii + 1] - pointY;
        if (bx === 0 && by === 0) return false; // point on edge
        if (ay === by) continue;
        lup = by > ay;
    }

    let depth = 0;
    for (let i = 0; i < n; i++) {
        ax = bx;
        ay = by;
        bx = polygon[2 * i] - pointX;
        by = polygon[2 * i + 1] - pointY;
        if (ay < 0 && by < 0) continue; // both 'up' or both 'down'
        if (ay > 0 && by > 0) continue; // both 'up' or both 'down'
        if (ax < 0 && bx < 0) continue; // both points on the left

        if (ay === by && Math.min(ax, bx) < 0) return true;
        if (ay === by) continue;

        let lx = ax + ((bx - ax) * -ay) / (by - ay);
        if (lx === 0) return false; // point on edge
        if (lx > 0) depth++;
        if (ay === 0 && lup && by > ay) depth--; // hit vertex, both up
        if (ay === 0 && !lup && by < ay) depth--; // hit vertex, both down
        lup = by > ay;
    }
    return (depth & 1) === 1;
}

dmgis.olmap.Tools.prototype.pointInRect = function(rect, pointX, pointY) {
    let a = (rect[0] - rect[0]) * (pointY - rect[1]) - (rect[3] - rect[1]) * (pointX - rect[0]);
    let b = (rect[2] - rect[0]) * (pointY - rect[3]) - (rect[3] - rect[3]) * (pointX - rect[0]);
    let c = (rect[2] - rect[2]) * (pointY - rect[3]) - (rect[1] - rect[3]) * (pointX - rect[2]);
    let d = (rect[0] - rect[2]) * (pointY - rect[1]) - (rect[1] - rect[1]) * (pointX - rect[2]);
    return (a > 0 && b > 0 && c > 0 && d > 0) || (a < 0 && b < 0 && c < 0 && d < 0)
}
